package com.alliky.core.net;

import com.alliky.core.base.IView;
import com.tamsiree.rxkit.view.RxToast;

import io.reactivex.observers.DisposableObserver;

public abstract class BaseObserver<T> extends DisposableObserver<T> {

    IView mView;
    boolean isLoading = true;

    public BaseObserver() {
    }

    public BaseObserver(IView view) {
        this.mView = view;
    }

    public BaseObserver(IView view, boolean isLoading) {
        mView = view;
        this.isLoading = isLoading;
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (this.mView != null && isLoading) {
            this.mView.showLoading();
        }
    }

    @Override
    public void onComplete() {
        if (this.mView != null) {
            if (isLoading) {
                this.mView.hideLoading();
            }
        }
    }

    @Override
    public void onError(Throwable e) {
        if (this.mView != null) {
            if (isLoading) {
                this.mView.hideLoading();
            }
            mView.finishRefresh();
            mView.finishLoadMore();

        }
        e.printStackTrace();
        if (e instanceof ResponseThrowable) {
            ResponseThrowable throwable = (ResponseThrowable) e;
            mView.showError(throwable.code, throwable.message);
            return;
        } else {
            //其他全部甩锅给网络异常
            RxToast.normal("网络异常");
        }
    }

    @Override
    public void onNext(T t) {
        onResult(t);
    }

    /**
     * 成功的回调
     */
    protected abstract void onResult(T t);
}
